﻿using System.ComponentModel;
using System.Windows.Forms;
using Map;
using Map_Creator.MapInfo;
using Map_Creator.Painters;
using Microsoft.Xna.Framework;

namespace Map_Creator.AnimatedTileEditor
{
    public partial class TileSetControl : XNA.GraphicsDeviceControl
    {
        private TileSet tileSet;
        private Selection selection;

        public TileSetControl()
        {
            InitializeComponent();
        }

        public TileSetControl(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }

        public void Initialize(TileSet set)
        {
            tileSet = set;
            selection = new Selection(tileSet.AssociatedMap.TileSize, new Point(1, 1));
        }

        protected override void Draw(PaintEventArgs e)
        {
            GraphicsDevice.Clear(new Color(BackColor.R, BackColor.G, BackColor.B));
            // no back buffer is used so we need to paint it all over again each call
            xnaGraphics.Begin();

            xnaGraphics.Draw(tileSet.TilesImage, Vector2.Zero,Color.White);
            selection.OnDraw(xnaGraphics,new Rectangle(0,0,Width,Height));

            xnaGraphics.End();
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;

            var position = e.Location;
            position.X = MathEx.Clamp(position.X, 0, Width - 1);
            position.Y = MathEx.Clamp(position.Y, 0, Height - 1);

            var tilePosition = new Point(position.X / tileSet.AssociatedMap.TileSize, position.Y / tileSet.AssociatedMap.TileSize);

            selection.OnMouseDown(tilePosition, e.Button);
            Invalidate();
        }

        public TileStruct GetSelectedTile()
        {
            var pos = selection.Rectangle.Location;
            return tileSet.Tiles[pos.X, pos.Y];
        }

    }
}
